package com.fang.零拷贝;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

/**
 * @author Fang Ruichuan
 * @date 2022-12-16 12:25
 */
public class ByteBufUtil {
    // 打印
    public static void log(ByteBuf buf) {
        final int length = buf.readableBytes();
        int rows = length >> 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder str = new StringBuilder(rows * 80 * 2)
                .append("read index: ").append(buf.readerIndex())
                .append(" write index: ").append(buf.writerIndex())
                .append(" capacity: ").append(buf.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(str, buf);
        System.out.println(str);
    }

    public static void main(String[] args) {
        System.out.println(32 / 16);
        System.out.println(32 >> 4);
        System.out.println("------------------------");
        // 创建ByteBuf
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(10);
        // 向 byteBuf 缓冲区写入数据
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            str.append("nx");
        }
        byteBuf.writeBytes(str.toString().getBytes());


        // 打印当前 byteBuf
        ByteBufUtil.log(byteBuf);

        // 切片过程中并没有发生数据复制
        final ByteBuf slice = byteBuf.slice(0, 5);
        final ByteBuf slice1 = byteBuf.slice(5, 5);

        // 打印第一个切片
        ByteBufUtil.log(slice);
        // 打印第二个切片
        ByteBufUtil.log(slice1);

        slice.setByte(0, 'a');
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        // 打印第一个切片
        ByteBufUtil.log(slice);
        // 打印原始数组
        ByteBufUtil.log(byteBuf);
    }
}
